package com.banciyuan.bcywebview.biz.post.write.series;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.NovelApi;
import com.banciyuan.bcywebview.base.activity.BaseActivity;
import com.banciyuan.bcywebview.base.helper.ActionbarHelper;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.view.dialog.ConfirmDialog;
import com.banciyuan.bcywebview.base.view.dialog.MyProgressDialog;
import com.banciyuan.bcywebview.base.view.toast.MyToast;
import com.banciyuan.bcywebview.biz.post.Listener.OnTextChangeListener;
import com.banciyuan.bcywebview.biz.post.auto.AutoComplateHelper;
import com.banciyuan.bcywebview.biz.post.auto.AutoComplateNoLimteAdapter;
import com.banciyuan.bcywebview.biz.post.auto.IGetAutoComplate;
import com.banciyuan.bcywebview.biz.post.write.WriteArticleActivity;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.banciyuan.bcywebview.utils.sp.SPConstant;
import com.banciyuan.bcywebview.utils.sp.SPHelper;
import com.banciyuan.bcywebview.utils.universalimageloader.core.ImageLoader;
import com.banciyuan.bcywebview.utils.universalimageloader.utils.ImageOptions;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import de.greenrobot.daoexample.model.CreateSeriesItem;
import de.greenrobot.daoexample.model.WriteCover;

/**
 * Created by hy on 2015/12/31.
 */
public class CreateSeriesActivity extends BaseActivity implements View.OnClickListener, ActionbarHelper.OnActionCallbacks {
    private static final int GO_POSTWRITE = 1002;
    public static final int GO_SETINFO = 1001;
    protected static final String dongjin = "fanfic";
    protected static final String undongjin = "fiction";

    protected ActionbarHelper mActionbarHelper;
    private View mActionBarView;
    private TextView tv_confirm;
    protected RadioButton rb_one;
    protected RadioButton rb_two;
    private View viewWorkInfo;
    private View viewWorkLine;
    protected EditText etSeriesTitle;
    private ImageView info_label;
    private TextView info_write;
    protected RequestQueue mQueue;
    protected MyProgressDialog mDialog;
    private String work = "";
    private String tag = "";
    private boolean posting = false;
    private LinearLayout llWriteCovers;
    private ImageLoader imageLoader;
    protected int selectCoverIndex = 0;
    protected boolean hideAuto = false;

    protected List<WriteCover> writeCoverList;
    protected CreateSeriesItem seriesItem = new CreateSeriesItem();
    protected AutoCompleteTextView etSeriesWork;
    private AutoComplateNoLimteAdapter autoComplateAdapter;
    private List<String> slist = new ArrayList<String>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.create_series_layout);
        getItem(savedInstanceState);
        initArgs();
        initProgressbar();
        initUi();
        initActionbar();
        initAction();
        initData();
        getCovers();
    }

    @Override
    protected void initArgs() {
        imageLoader = ImageLoader.getInstance();
        seriesItem.setType(dongjin);//set default type
        mQueue = VolleyQueue.getRquest(this);
        Intent intent = getIntent();
        work = intent.getStringExtra(gotoUtil.INTENT_VALUE_ONE);
        tag = intent.getStringExtra("tags");
    }

    private void getItem(Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            if (savedInstanceState.getSerializable("seriesItem") != null) {
                seriesItem = (CreateSeriesItem) savedInstanceState.getSerializable("seriesItem");
            } else {
                seriesItem = new CreateSeriesItem();
            }
        } else {
            seriesItem = new CreateSeriesItem();
        }
    }

    @Override
    protected void initActionbar() {
        mActionBarView = findViewById(R.id.base_action_bar);
        mActionbarHelper = new ActionbarHelper(this, mActionBarView);
        mActionbarHelper.setTitle(getString(R.string.create_series));
        mActionbarHelper.addItemOneText(getString(R.string.mydialog_comfirm));
        tv_confirm = (TextView) findViewById(R.id.base_action_bar_home_text_item);
        tv_confirm.setOnClickListener(this);
        mActionbarHelper.setActionCallbacks(this);
    }

    @Override
    protected void initUi() {
        findViewById(R.id.ll_rights_set).setVisibility(View.GONE);
        rb_one = (RadioButton) findViewById(R.id.radio_tongren);
        rb_two = (RadioButton) findViewById(R.id.radio_untongren);
        viewWorkInfo = findViewById(R.id.ll_work_info);
        viewWorkLine = findViewById(R.id.work_line);


        etSeriesWork = (AutoCompleteTextView) findViewById(R.id.series_work);
        etSeriesWork.setText(work);
        etSeriesTitle = (EditText) findViewById(R.id.series_title);
        info_write = (TextView) findViewById(R.id.info_has_write);
        info_label = (ImageView) findViewById(R.id.info_label);
        ((TextView) findViewById(R.id.info_text)).setText(getString(R.string.add_title_series));

        llWriteCovers = (LinearLayout) findViewById(R.id.ll_write_covers);

        DialogInterface.OnClickListener cancelOnClick = null;
        DialogInterface.OnCancelListener onCancelClick = null;
        cancelOnClick = new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                mDialog.dismiss();
            }
        };
        MyProgressDialog.Builder mBuilder = new MyProgressDialog.Builder(this);
        mDialog = mBuilder.setCancelButton(cancelOnClick).setOnCancelButton(onCancelClick).create();
    }

    @Override
    protected void initAction() {
        findViewById(R.id.ll_info_set).setOnClickListener(this);
        ((RadioGroup) findViewById(R.id.radio_tongjin)).setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.radio_tongren:
                        viewWorkInfo.setVisibility(View.VISIBLE);
                        viewWorkLine.setVisibility(View.VISIBLE);
                        seriesItem.setType(dongjin);
                        break;
                    case R.id.radio_untongren:
                        viewWorkInfo.setVisibility(View.GONE);
                        viewWorkLine.setVisibility(View.GONE);
                        seriesItem.setType(undongjin);
                        break;
                }
            }
        });
        final IGetAutoComplate iGetAutoComplate = new IGetAutoComplate() {
            @Override
            public void getComplateList(String s, boolean show) {
                dealAutoJson(s, show);
            }
        };
        etSeriesWork.addTextChangedListener(new OnTextChangeListener() {
            @Override
            public void afterTextChanged(Editable s) {
                if (!hideAuto) {
                    if (!etSeriesWork.isPerformingCompletion()) {
                        if (!TextUtils.isEmpty(s.toString())) {
                            String url = HttpUtils.BASE_URL + NovelApi.getComplete();
                            AutoComplateHelper autoHelper = new AutoComplateHelper(CreateSeriesActivity.this, iGetAutoComplate, "work");
                            autoHelper.findServerTitle(s, true, url);
                        }
                        if (TextUtils.isEmpty(s.toString())) {
                            etSeriesWork.dismissDropDown();
                        }
                    }
                } else {
                    hideAuto = false;
                }
            }
        });

    }

    private void getCovers() {
        String url = HttpUtils.BASE_URL + NovelApi.getDefaultcover();
        List<BcyPair> pairs = new ArrayList<BcyPair>();
        pairs.add(new BcyPair(HttpUtils.USER_TOKEN, UserDataHelper.getInstance(CreateSeriesActivity.this).getToken()));
        Map<String, String> map = HttpUtils.getData(pairs);
        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                if (StatusCodeUtils.dealStatusCode(s, CreateSeriesActivity.this)) {
                    try {
                        Gson gson = new Gson();
                        JSONObject jsonObject = new JSONObject(s);
                        String result = jsonObject.getString(HttpUtils.UPLOAD_DATA);
                        writeCoverList = gson.fromJson(result,
                                new TypeToken<List<WriteCover>>() {
                                }.getType());
                        setCovers();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
            }
        };
        StringRequestParam requestParam = new StringRequestParam(Request.Method.POST, url, map, onSucc, onError);
        mQueue.add(requestParam);
    }

    private void setCovers() {
        if (null == writeCoverList)
            return;
        LayoutInflater layoutInflater = LayoutInflater.from(this);
        llWriteCovers.removeAllViews();
        for (int i = 0; i < writeCoverList.size(); i++) {
            View viewWriteCover = layoutInflater.inflate(R.layout.write_cover_item, llWriteCovers, false);
            if (i == 0)
                viewWriteCover.findViewById(R.id.iv_write_cover_checked).setVisibility(View.VISIBLE);
            final ImageView ivWriteCover = (ImageView) viewWriteCover.findViewById(R.id.iv_write_cover);
            ivWriteCover.setTag(i);
            ivWriteCover.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    for (int i = 0; i < llWriteCovers.getChildCount(); i++) {
                        llWriteCovers.getChildAt(i).findViewById(R.id.iv_write_cover_checked).setVisibility(View.INVISIBLE);
                    }
                    selectCoverIndex = (int) ivWriteCover.getTag();
                    llWriteCovers.getChildAt(selectCoverIndex).findViewById(R.id.iv_write_cover_checked).setVisibility(View.VISIBLE);
                }
            });
            imageLoader.displayImage(writeCoverList.get(i).getPath(), ivWriteCover, ImageOptions.options);
            llWriteCovers.addView(viewWriteCover);
        }
        if (!TextUtils.isEmpty(seriesItem.getCover()) && !seriesItem.getCover().equals("0")) {
            for (int i = 0; i < llWriteCovers.getChildCount(); i++) {
                llWriteCovers.getChildAt(i).findViewById(R.id.iv_write_cover_checked).setVisibility(View.INVISIBLE);
            }
            selectCoverIndex = Integer.parseInt(seriesItem.getCover()) - 1;
            llWriteCovers.getChildAt(selectCoverIndex).findViewById(R.id.iv_write_cover_checked).setVisibility(View.VISIBLE);
        }
    }

    private void dealAutoJson(String s, boolean show) {
        try {
            if (StatusCodeUtils.dealStatusCode(s, this)) {
                JSONObject jsonObject = new JSONObject(s);
                JSONArray jsonArray = jsonObject.getJSONArray("data");
                slist.clear();
                for (int i = 0; i < jsonArray.length(); i++) {
                    slist.add(jsonArray.getString(i));
                }
                autoComplateAdapter = new AutoComplateNoLimteAdapter(slist, this, etSeriesWork.getText().toString());
                etSeriesWork.setAdapter(autoComplateAdapter);
            }
            if (show) {
                if (!isFinishing()) {
                    etSeriesWork.showDropDown();
                }
            }
        } catch (Exception e) {
        }
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.ll_info_set:
                saveItem();
                intent.setClass(CreateSeriesActivity.this, SeriesInfoActivity.class);
                intent.putExtra(gotoUtil.INTENT_VALUE_ONE, seriesItem);
                startActivityForResult(intent, GO_SETINFO);
                break;
            case R.id.base_action_bar_home_text_item:
                if (posting)
                    return;
                posting = true;
                Gson gson = new Gson();
                if (valid()) {
                    mDialog.show();
                    saveItem();
                    removeRepeatTag();
                    String json = gson.toJson(seriesItem);
                    postSeries(json);
                }
                posting = false;
                break;
        }
    }

    private void removeRepeatTag() {
        String repeatTag = null;
        if (rb_one.isChecked()) {
            for (String tag : seriesItem.getTags()) {
                if (tag.equals(seriesItem.getWork()))
                    repeatTag = tag;
            }
        }
        if (!TextUtils.isEmpty(repeatTag))
            seriesItem.getTags().remove(repeatTag);
    }

    private void saveItem() {
        if(seriesItem==null)return;
        seriesItem.setTitle(etSeriesTitle.getText().toString().trim());
        seriesItem.setWork(etSeriesWork.getText().toString().trim());
        if(writeCoverList!=null){
            seriesItem.setCover(writeCoverList.get(selectCoverIndex).getCover());
        }
        if (rb_one.isChecked()) {
            seriesItem.setWork(etSeriesWork.getText().toString().trim());
        } else {
            seriesItem.setWork("");
        }
    }

    private void postSeries(String json) {
        String url = HttpUtils.BASE_URL + NovelApi.getNewnovelset();
        List<BcyPair> pairs = new ArrayList<BcyPair>();
        pairs.add(new BcyPair(HttpUtils.USER_TOKEN, UserDataHelper.getInstance(CreateSeriesActivity.this).getToken()));
        pairs.add(new BcyPair(HttpUtils.UPLOAD_DATA, json));
        Map<String, String> map = HttpUtils.getData(pairs);
        Response.Listener<String> onSucc = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                if (StatusCodeUtils.dealStatusCode(s, CreateSeriesActivity.this)) {
                    try {
                        JSONObject jsonObject = new JSONObject(s);
                        JSONObject result = jsonObject.getJSONObject(HttpUtils.UPLOAD_DATA);
                        String wns_id = result.getString("wns_id");
                        Intent intent = new Intent(CreateSeriesActivity.this, WriteArticleActivity.class);
                        intent.putExtra(gotoUtil.INTENT_VALUE_ONE, seriesItem.getTitle());
                        intent.putExtra(gotoUtil.INTENT_VALUE_TWO, "0");
                        intent.putExtra(gotoUtil.INTENT_VALUE_THREE, seriesItem.getType());
                        intent.putExtra(gotoUtil.INTENT_VALUE_FOUR, seriesItem.getWork());
                        intent.putExtra(gotoUtil.INTENT_VALUE_FIVE, wns_id);
                        intent.putExtra(gotoUtil.INTENT_VALUE_SIX, seriesItem.getCover());
                        intent.putExtra("tags", tag);
                        intent.putExtra("tag_array", (Serializable) seriesItem.getTags());
                        startActivityForResult(intent, GO_POSTWRITE);
                        saveTagInDiskMemory();
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                } else {
                    mDialog.dismiss();
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                mDialog.dismiss();
                MyToast.show(CreateSeriesActivity.this, getString(R.string.series_post_fail));
            }
        };

        StringRequestParam requestParam = new StringRequestParam(Request.Method.POST, url, map, onSucc, onError);
        mQueue.add(requestParam);
    }

    private boolean valid() {
        if (TextUtils.isEmpty(etSeriesTitle.getText().toString().trim())) {
            MyToast.show(CreateSeriesActivity.this, getString(R.string.title_cant_benull));
            return false;
        }
        if (dongjin.equals(seriesItem.getType()) && TextUtils.isEmpty(etSeriesWork.getText().toString().trim())) {
            MyToast.show(CreateSeriesActivity.this, getString(R.string.work_cant_benull));
            return false;
        }
        if (writeCoverList == null || selectCoverIndex >= writeCoverList.size()) {
            MyToast.show(CreateSeriesActivity.this, getString(R.string.write_cover_benull));
            return false;
        }
        return true;
    }

    private void saveTagInDiskMemory() {
        Gson gson = new Gson();
        String tagStrOriginal = SPHelper.getString(this, SPConstant.SPNAME_MEMORYTAG + UserDataHelper.getInstance(this).getUid(), SPConstant.WRITETAG, "[]");
        LinkedList<String> memoryTagList = gson.fromJson(tagStrOriginal, new TypeToken<LinkedList<String>>() {
        }.getType());
        memoryTagList.addAll(0, seriesItem.getTags());
        while (memoryTagList.size() > 10) {
            memoryTagList.removeLast();
        }
        String tagStr = gson.toJson(new LinkedHashSet<>(memoryTagList));
        SPHelper.putString(this, SPConstant.SPNAME_MEMORYTAG + UserDataHelper.getInstance(this).getUid(), SPConstant.WRITETAG, tagStr);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == GO_POSTWRITE) {
            setResult(resultCode);
            if (null != mDialog && mDialog.isShowing())
                mDialog.dismiss();
            finish();
        }
        if (requestCode == GO_SETINFO) {
            seriesItem = (CreateSeriesItem) data.getSerializableExtra("seriesItem");
            boolean flag = data.getBooleanExtra("change", false);
            if (flag) {
                info_label.setImageDrawable(getResources().getDrawable(R.drawable.more_info_pink));
                info_write.setVisibility(View.VISIBLE);
            } else {
                info_label.setImageDrawable(getResources().getDrawable(R.drawable.more_info_gray));
                info_write.setVisibility(View.GONE);
            }
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putSerializable("seriesItem", seriesItem);
    }

    @Override
    public void onBackPressed() {
        onBack();
    }

    private void onBack() {
        if (!mDialog.isShowing()) {
            ConfirmDialog.Builder builder = new ConfirmDialog.Builder(this);
            builder.setDescString(getString(R.string.not_save_warn))
                    .setActionString(getString(R.string.continue_post))
                    .setCancelString(getString(R.string.cancel_post))
                    .setCancelClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            finish();
                        }
                    }).create().show();
        } else {
            mDialog.dismiss();
        }
    }

    @Override
    public void onBackClick() {
        onBack();
    }

    @Override
    public void onActionClick(int id) {

    }

}
